import React, { PureComponent } from 'react';
import { Table,Input, message,Select, Checkbox,Card } from 'antd';
import Ellipsis from '@/components/Ellipsis';
import PateoAuthButtons from "@/common/PateoAuthButtons/PateoAuthButtons";
import moment from "moment";
import IndexModal from './indexModal';
import EditModal from './editModal';
import { connect } from 'dva';
import styles from './index.less';
import style from '../../../components/common/PateoTable/TableList.less';
import MaskText from '@/components/MaskText';

const tempHash = {  
    list: '列表',
    add: '新增',
    detail: '详情',
    map: '地图',
    more: '更多筛选'
  }
  @connect((state) => ({
    common: state.common,
    menu: state.menu,
    fieldManage: state.fieldManage,
  }))
export default class TableFormField extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      tableLoading: false,
      data: [], // 列表数据源
      updateData: {}, // 编辑时待提交数据
      indexModalVisible: false, // 字段排序弹窗
      checkedNum: [], // 已选中的数字顺序
      editModalVisible: false, // 修改弹窗
      fieldDetail:{}, //字段详情信息
    };
  }
  componentDidMount() {
    this.props.onRef(this)
  }
  componentWillMount() {
      this.getList();
  }
 
  addPreinstall = data => {
    return data.map(i => {
      const sameTitle = data.some(j => (j.name === i.name && i.fieldId !== j.fieldId));
      if (sameTitle && i.fieldId) {
        i.name = `${i.name}(预设)`
      }
      return i;
    })
  }
  //获取列表
  getList =() =>{
    this.setState({
      tableLoading: true,
    });
    const {dispatch}=this.props;
    dispatch({
      type: "fieldManage/postObjWithRes",
      payload: {
        url: "/mscreditbusiness/credit/merchant/field/list",
      },
      callback: (response) => {
        if (response && response.statusCode == "0" && response.data) {
          const list = this.addPreinstall(response.data);
          for (let i in list) {
            list[i].key = Number(i)
          }
          // 获取1-300使用过的数字
          const numList = list.map((item) =>{
            if(item.index){
              return item.index;
            }
          })
          const newNumList =[];
          numList.forEach(item =>{// 去除数组中undefined元素
            if(item){
              newNumList.push(item)
            }
          })
           this.setState({
            data: list,
            checkedNum: newNumList
           })
        } else {
          if (response.statusCode !== "0") {
            message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
          updateData: {}
        });
      },
    });
  }
  setData = (data) => {
    console.log('data', data)
   }
  // 查询
  handleSearch =(fieldsValue) =>{// 每次查询前先获取最新list数据再进行条件筛选
    this.setState({
      tableLoading: true,
    });
    const {dispatch}=this.props;
    dispatch({
      type: "fieldManage/postObjWithRes",
      payload: {
        url:"/mscreditbusiness/credit/merchant/field/list"
      },
      callback: (response) => {//每次查询前先获取最新最新列表
        if (response && response.statusCode == "0" && response.data) {
          const list = this.addPreinstall(response.data); //此时list是新数据
          for (let i in list) {
            list[i].key = Number(i)
          }
          // 获取1-300使用过的数字
          const numList = list.map((item) =>{
            if(item.index){
              return item.index;
            }
          })
          const newNumList =[];
          numList.forEach(item =>{// 去除数组中undefined元素
            if(item){
              newNumList.push(item)
            }
          })
          if(fieldsValue.name !== undefined || fieldsValue.groupId !== undefined){ //如果查询条件存在
          const searchData = list?.map((item) =>{
            if(fieldsValue.name && fieldsValue.groupId==undefined){
                 if(item.name === fieldsValue.name){
                  return item
                 }
            }else if(fieldsValue.name==undefined && fieldsValue.groupId){
              if(item.groupId == fieldsValue.groupId){
                return item
               }
            }else if(fieldsValue.groupId && fieldsValue.name){
              if(item.name === fieldsValue.name && item.groupId == fieldsValue.groupId){
                return item
               }
            }else{
              return
            } 
          })
          const newSearchData =[];
          searchData.forEach(item =>{
            if(item){
              newSearchData.push(item)
            }
          })
           this.setState({
            data: newSearchData,
            checkedNum: newNumList
           })
          }else{
            this.setState({
              data: list,
              checkedNum: newNumList
             })
          }
        } else {
          if (response.statusCode !== "0") {
            message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
          updateData: {}
        });
      },
    });
  }
  // 获取当前行的信息
  getRowByKey(key) {
    return this.state.data.filter(item => item.key === key)[0];
  }
  cacheOriginData = {};
  // 切换编辑
  toggleEditable=(e, key) =>{
    e.preventDefault();
    if( !(JSON.stringify(this.state.updateData) === '{}')){// 如果已有值，说明已经点击过“设置应用场景
      message.warning('请先保存修改内容');
      return
    }
    const target = this.getRowByKey(key);
    const {updateData} = this.state;// 点击编辑先注入该行uuid.index数据，以在点击另一行编辑时可以判断是否有行处于编辑状态
    updateData.uuid = target.uuid;
    updateData.index = target.index;
    updateData.key = target.key;
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        this.cacheOriginData[key] = { ...target };
      }
      target.editable = !target.editable;
      this.setState({ data: [...this.state.data] });
    }
  }
  handleFieldChange=(e, fieldName, key)=> {
    const {updateData} = this.state;
    updateData[fieldName] = e;
    const newData = [...this.state.data];
    const target = this.getRowByKey(key);
    if (target) {
      target[fieldName]?.map(item=>{
        if(e.includes(item.scene)){
          item.status = 1
        } else{
          item.status = 0
        }
      });
      this.setState({ data: newData });
    }
  }
  saveRow=(e, key)=> {
    const currentData = this.getRowByKey(key);// 当前data数据
    e.persist();
      const {updateData} = this.state;
      // if(updateData.index === null){
      //   message.error('请选择字段顺序！');
      //   return;
      // }
      const params={};
      params.uuid = updateData.uuid;
      params.index = updateData.index;
      // 筛选出不属于系统预设场景的场景
      if(updateData.creditList){// 有勾选改变勾选项
        const presetScene = [];
        currentData.creditList.map(item =>{//当前预设场景arry
          if(item.type === 1){
            presetScene.push(item.scene)
          }
        })
        const checkedScene = [];
        updateData.creditList.map(item =>{
          if(!presetScene.includes(item)){
            checkedScene.push(item);
          }
        })
        params.creditList = checkedScene;
      }else{ // 未改变勾选项
        const presetScene = [];
        currentData.creditList.map(item =>{//当前预设场景arry
          if(item.type === 1){
            presetScene.push(item.scene)
          }
        })
        const checkedScene = [];
        const checkedData = [];//已选择过的数据
        currentData.creditList.map(item =>{//当前预设场景arry
          if(item.status === 1){
            checkedData.push(item.scene)
          }
        })
        checkedData.map(item =>{
          if(!presetScene.includes(item)){
            checkedScene.push(item);
          }
        })
        params.creditList = checkedScene;
      }
      if(updateData.warningList){
        const presetScene = [];
        currentData.warningList.map(item =>{//从当前data数据中筛选出预设场景arry
          if(item.type === 1){
            presetScene.push(item.scene)
          }
        })
        const checkedScene = [];
        updateData.warningList.map(item =>{//筛选出勾选的非预设场景
          if(!presetScene.includes(item)){
            checkedScene.push(item);
          }
        })
        params.warningList = checkedScene;
      }else{
        const presetScene = [];
        currentData.warningList.map(item =>{//当前预设场景arry
          if(item.type === 1){
            presetScene.push(item.scene)
          }
        })
        const checkedScene = [];
        const checkedData = [];//已选择过的数据
        currentData.warningList.map(item =>{//当前预设场景arry
          if(item.status === 1){
            checkedData.push(item.scene)
          }
        })
        checkedData.map(item =>{
          if(!presetScene.includes(item)){
            checkedScene.push(item);
          }
        })
        params.warningList = checkedScene;
      }
      if(updateData.overdueList){
        const presetScene = [];
        currentData.overdueList.map(item =>{//当前预设场景arry
          if(item.type === 1){
            presetScene.push(item.scene)
          }
        })
        const checkedScene = [];
        updateData.overdueList.map(item =>{
          if(!presetScene.includes(item)){
            checkedScene.push(item);
          }
        })
        params.overdueList = checkedScene;
      }else{
        const presetScene = [];
        currentData.overdueList.map(item =>{//当前预设场景arry
          if(item.type === 1){
            presetScene.push(item.scene)
          }
        })
        const checkedScene = [];
        const checkedData = [];//已选择过的数据
        currentData.overdueList.map(item =>{//当前预设场景arry
          if(item.status === 1){
            checkedData.push(item.scene)
          }
        })
        checkedData.map(item =>{
          if(!presetScene.includes(item)){
            checkedScene.push(item);
          }
        })
        params.overdueList = checkedScene;
      }
      if(updateData.mileageList){
        const presetScene = [];
        currentData.mileageList.map(item =>{//当前预设场景arry
          if(item.type === 1){
            presetScene.push(item.scene)
          }
        })
        const checkedScene = [];
        updateData.mileageList.map(item =>{
          if(!presetScene.includes(item)){
            checkedScene.push(item);
          }
        })
        params.mileageList = checkedScene;
      }else{
        const presetScene = [];
        currentData.mileageList.map(item =>{//当前预设场景arry
          if(item.type === 1){
            presetScene.push(item.scene)
          }
        })
        const checkedScene = [];
        const checkedData = [];//已选择过的数据
        currentData.mileageList.map(item =>{//当前预设场景arry
          if(item.status === 1){
            checkedData.push(item.scene)
          }
        })
        checkedData.map(item =>{
          if(!presetScene.includes(item)){
            checkedScene.push(item);
          }
        })
        params.mileageList = checkedScene;
      }
      //对风控场景的数据处理
      if(updateData.riskcontrolvehicleList){
        const presetScene = [];
        currentData.riskcontrolvehicleList.map(item =>{//当前预设场景arry
          if(item.type === 1){
            presetScene.push(item.scene)
          }
        })
        const checkedScene = [];
        updateData.riskcontrolvehicleList.map(item =>{
          if(!presetScene.includes(item)){
            checkedScene.push(item);
          }
        })
        params.riskcontrolvehicleList = checkedScene;
      }else{
        const presetScene = [];
        currentData.riskcontrolvehicleList.map(item =>{//当前预设场景arry
          if(item.type === 1){
            presetScene.push(item.scene)
          }
        })
        const checkedScene = [];
        const checkedData = [];//已选择过的数据
        currentData.riskcontrolvehicleList.map(item =>{//当前预设场景arry
          if(item.status === 1){
            checkedData.push(item.scene)
          }
        })
        checkedData.map(item =>{
          if(!presetScene.includes(item)){
            checkedScene.push(item);
          }
        })
        params.riskcontrolvehicleList = checkedScene;
      }
      const {dispatch}=this.props;
      dispatch({
        type: "fieldManage/postObjWithRes",
        payload: {
          url:"/mscreditbusiness/credit/merchant/field/scene", ...params
        },
        callback: (response) => {
          if (response && response.statusCode == "0") {
            this.cancel(e);
            message.success("保存成功！");
          } else {
            if (response.statusCode !== "0") {
              // message.error(response.statusMessage);
            }
          }
        },
      });
      // this.cancel(e);
  }
  // 取消修改
  cancel=(e, key)=> {
    this.getList();
    this.setState({ 
      updateData: {}
    });
    e.preventDefault();
  }
   // 字段排序弹窗
   fieldIndexModal = (e, key) => {
    this.setState({
      indexModalVisible: true,
    });
  };
  closeIndexModal = () => {
    this.setState({
      indexModalVisible: false,
    });
  }
  // 获取选取的index值
  getIndexChecked =(e) =>{
    if(e){
    const newData = [...this.state.data];
    const target = this.getRowByKey(this.state.updateData.key);
    if (target) {
      target['index'] = e;
      this.setState({ 
        data: newData 
      });
    }
    const {updateData} = this.state;
    updateData.index = e;
  }
  }
  onRef = (ref) => {
    this.editRef = ref
  }
  // 修改
  handleEdit=(key)=>{
  const { dispatch,form }=this.props;
    dispatch({
      type: 'fieldManage/postDataWithRes',
      payload: { 
        url: '/mscreditbusiness/credit/merchant/field/detail',
        uuid: key,
      },
      callback: response=>{
        if (response.statusCode === '0') {
          const fieldDetail = response.data;
          this.setState({
            fieldDetail: response.data,
            editModalVisible: true,
          });
          this.editRef.showModal(fieldDetail);
        } else {
          // message.error(response.statusMessage);
        }
      }
    })
  }
  closeEditModal = () => {
    this.setState({
      editModalVisible: false,
    });
    this.getList();
  }
  // 启用
  handleEnable=(key) =>{
    const { dispatch }=this.props;
    const params={};
    params.uuid = key;
    params.status = 1;
    dispatch({
      type: 'fieldManage/postDataWithRes',
      payload: { 
        url: '/mscreditbusiness/credit/merchant/field/status',
        ...params
      },
      callback: response=>{
        if (response.statusCode === '0') {
          message.success('启用成功');
          this.getList();
        } else {
          message.error(response.statusMessage);
        }
      }
    })
  }
  // 停用
  handleDisable=(key)=>{
    const { dispatch }=this.props;
    const params={};
    params.uuid = key;
    params.status = 2;
    dispatch({
      type: 'fieldManage/postDataWithRes',
      payload: { 
        url: '/mscreditbusiness/credit/merchant/field/status',
        ...params
      },
      callback: response=>{
        if (response.statusCode === '0') {
          message.success('停用成功');
          this.getList();
        } else {
          message.error(response.statusMessage);
        }
      }
    })
  }
  // 删除
  handleDelete=(key)=>{
    const { dispatch }=this.props;
    const params={};
    params.uuid = key;
    dispatch({
      type: 'fieldManage/postDataWithRes',
      payload: { 
        url: '/mscreditbusiness/credit/merchant/field/delete',
        ...params
      },
      callback: response=>{
        if (response.statusCode === '0') {
          message.success('删除成功');
          this.props.getNum();
          this.getList();
        } else {
          message.error(response.statusMessage);
        }
      }
    })
  }
  render() {
    const { isEnable, isUpdate, isDel, isUnable, isSet, isSave, isCancel,groupList,}=this.props;
    const {indexModalVisible,tableLoading,editModalVisible,} = this.state;
    const columns = [
      {
        title: '行号',
        dataIndex: 'no',
        render: (text, record, index) => {
          return index + 1;
        },
      },
      {
        title: '字段名称',
        dataIndex: 'name',
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '所属分组',
        dataIndex: 'groupName',
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '字段类型',
        dataIndex: 'type',
        render: (text, record) => {
          if(record.name === '预警信息列表' || record.name === '风控操作记录列表'){
            return '列表' 
          }
          else if (text == 1) {
            return '文本' 
          }else if(text == 2){
            return '下拉列表' 
          }else if(text == 3){
            return '数字'
          }else if(text == 4){
            return '日期'
          }else if(text == 5){
            return '时间'
          }else if(text == 6){
            return '日期时间'
          }else if(text == 7){
            return ' URL连接'
          }else{
            return ''
          }
        },
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: (text, record) => {
          if (text == 0) {
            return '未生效' 
          }else if(text == 1){
            return '生效中' 
          }else if(text == 2){
            return '已停用'
          }else{
            return ''
          }
        },
      },
      {
        title: '字段顺序',
        dataIndex: 'index',
        render: (text, record) => {
          if (record.editable) {
            return (
            <Input
              value={text}
              style={{ width: 50 }}
              onClick={e => this.fieldIndexModal(e, record.uuid)}
            />
            );
          }
          return text;
        },
      },
      {
      title: '授信车辆',
      dataIndex: 'creditList',
      key: 'creditList',
      width: "120px",
      render: (text, record) => {
          return (
            <Checkbox.Group 
            key={text.map(item =>{
              if(item.status == 1){
                return item.scene
              }
            })} 
            defaultValue={text.map(item =>{
                if(item.status == 1){
                  return item.scene
                }
              })}   
              onChange={e => this.handleFieldChange(e, 'creditList', record.key)}>
                {
              text.map((item, index) => (
                <div>
                  <Checkbox 
                      key={index} 
                      value={item.scene} 
                      disabled={!record.editable || item.type === 1}
                   >
                    {tempHash[item.scene]}
                   </Checkbox>
                   <br />
                   </div>
              ))
          }
          </Checkbox.Group> 
          )
      },
    },
    {
      title: '预警车辆',
      dataIndex: 'warningList',
      key: 'warningList',
      width: "120px",
      render: (text, record) => {
          return (
            <Checkbox.Group 
            key={text.map(item =>{ if(item.status == 1){return item.scene} })}  
            defaultValue={text.map(item =>{ if(item.status == 1){return item.scene}})}   
            onChange={e => this.handleFieldChange(e, 'warningList', record.key)}>{
              text.map((item, index) => (
                <div>
                <Checkbox 
                    key={index} 
                    value={item.scene} 
                    disabled={!record.editable || item.type === 1}
                 >
                  {tempHash[item.scene]}
                 </Checkbox>
                 <br />
                 </div>
            ))
          }
          </Checkbox.Group> 
          );
      },
    }, 
    {
      title: '逾期车辆',
      dataIndex: 'overdueList',
      key: 'overdueList',
      width: "120px",
      render: (text, record) => {
          return (
            <Checkbox.Group 
            key={text.map(item =>{
              if(item.status == 1){
                return item.scene
              }
            })}  
            defaultValue={text.map(item =>{
              if(item.status == 1){
                return item.scene
              }
            })}   
            onChange={e => this.handleFieldChange(e, 'overdueList', record.key)}>{
              text.map((item, index) => (
                <div>
                <Checkbox 
                    key={index} 
                    value={item.scene} 
                    disabled={!record.editable || item.type === 1}
                 >
                  {tempHash[item.scene]}
                 </Checkbox>
                  <br />
                  </div>
            ))
          }
          </Checkbox.Group> 
          );
      },
    },{
      title: '行驶里程',
      dataIndex: 'mileageList',
      key: 'mileageList',
      width: "120px",
      render: (text, record) => {
        return (
          <Checkbox.Group 
          key={text.map(item =>{
            if(item.status == 1){
              return item.scene
            }
          })}  
           defaultValue={text.map(item =>{
            if(item.status == 1){
              return item.scene
            }
          })}    
          onChange={e => this.handleFieldChange(e, 'mileageList', record.key)}>{
            text.map((item, index) => (
              <div>
              <Checkbox 
                  key={index} 
                  value={item.scene} 
                  disabled={!record.editable || item.type === 1}
               >
                {tempHash[item.scene]}
               </Checkbox>
                <br />
                </div>
          ))
        }
        </Checkbox.Group> 
        );
    },
    },{
      title: '风控异常车辆',
      dataIndex: 'riskcontrolvehicleList',
      key: 'riskcontrolvehicleList',
      width: "120px",
      render: (text, record) => {
        return (
          <Checkbox.Group 
          key={text.map(item =>{
            if(item.status == 1){
              return item.scene
            }
          })}  
           defaultValue={text.map(item =>{
            if(item.status == 1){
              return item.scene
            }
          })}    
          onChange={e => this.handleFieldChange(e, 'riskcontrolvehicleList', record.key)}>{
            text.map((item, index) => (
              <div>
              <Checkbox 
                  key={index} 
                  value={item.scene} 
                  disabled={!record.editable || item.type === 1}
               >
                {tempHash[item.scene]}
               </Checkbox>
                <br />
                </div>
          ))
        }
        </Checkbox.Group> 
        );
    },
    }, {
      title: '创建人',
      dataIndex: 'createBy',
      render: (text, record) => (
        record.fieldId ? "系统" : (
          <MaskText text={text} type="name" />
        )
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      render: (text) => {
        return text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : "";
      },
    },
    {
      title: '操作',
      key: 'action',
      align: "center",
      // width: "170px",
      fixed: 'right',
      render: (text, record) => {
        const btns = [];
        const updateBtn = {
          title: "修改",
          key: "update",
          onConfirm: () => this.handleEdit(record.uuid),
        };
        const deleteBtn = {
          title: "删除",
          Popconfirm: true,
          message: "确认要删除吗?",
          key: "delete",
          onConfirm: () => this.handleDelete(record.uuid),
        };
        const enableBtn = {
          title: "启用",
          Popconfirm: true,
          message: "确认要启用吗?",
          key: "enable",
          onConfirm: () => this.handleEnable(record.uuid),
        };
        const unableBtn = {
          title: "停用",
          Popconfirm: true,
          message: "确认要停用吗?",
          key: "unable",
          onConfirm: () => this.handleDisable(record.uuid),
        };
        const saveBtn = {
          title: "保存修改",
          key: "save",
          onConfirm: (e) => this.saveRow(e, record.key),
        };
        const cancelBtn = {
          title: "取消修改",
          key: "cancel",
          onConfirm: (e) => this.cancel(e, record.key),
        };
        const setBtn = {
          title: "设置应用场景",
          key: "set",
          onConfirm: (e) => this.toggleEditable(e, record.key),
        };

        if (record.editable) {// 处于编辑状态
          if(isSave) btns.push(saveBtn)
          if(isCancel) btns.push(cancelBtn)
        }else{
          if(record.status === 0) {//未生效 //非系统预设字段才能启用、停用、删除、修改
            if(isEnable && (record.fieldId === null )) btns.push(enableBtn)
            if(isUpdate && (record.fieldId === null )) btns.push(updateBtn)
            if(isDel && (record.fieldId === null )) btns.push(deleteBtn)
            if(isSet) btns.push(setBtn)
          }else if(record.status === 1){// 生效中
            if(isUnable && (record.fieldId === null )) btns.push(unableBtn)
            if(isSet) btns.push(setBtn)
          }else if(record.status === 2){
            if(isEnable && (record.fieldId === null )) btns.push(enableBtn)
            if(isSet) btns.push(setBtn)
          }
        }
        return (
          <PateoAuthButtons
            authStr="fieldManage"
            btns={btns}
          />
        );
      }, 
    }
  ];
    return (
      <div>
        <Card style={{ marginTop: 12 }} bordered={false}>
        <Table
          columns={columns}
          rowKey={record => record.key}
          dataSource={this.state.data}
          pagination={false}
          loading={tableLoading}
          onChange={this.handleTableChange}
          rowClassName={() => styles["editable-row"]}
          scroll={{ x: 'max-content'  }}
        />
        </Card>
         <IndexModal
            modalVisible={indexModalVisible}
            closeModal={this.closeIndexModal}
            dispatch={this.props.dispatch}
            checkedNum={this.state.checkedNum}
            getIndexChecked={this.getIndexChecked}
          />
          <EditModal
            onRef={this.onRef}
            modalVisible={editModalVisible}
            closeModal={this.closeEditModal}
            dispatch={this.props.dispatch}
            groupList={groupList}
            fieldDetail={this.state.fieldDetail}
          />
      </div>
    );
  }
}

